package com.mx.saco.security;


import com.mx.saco.util.Util;
import javax.faces.application.NavigationHandler;
import javax.faces.application.ViewExpiredException;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

public class AuthorizationListener implements PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {

        try {
            FacesContext facesContext = event.getFacesContext();
            String currentPage = facesContext.getViewRoot().getViewId();
            boolean isLoginPage = (currentPage.lastIndexOf("index.xhtml") > -1);
            boolean isExpiredSessionPage = (currentPage.lastIndexOf("expiredSession.xhtml") > -1);
            HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);

            if (session == null) {
                NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
                if (isExpiredSessionPage) {
                    nh.handleNavigation(facesContext, null, "expiredSessionPage");
                } else {
                    nh.handleNavigation(facesContext, null, "loginPage");
                }
            } else {
                Object currentUser = session.getAttribute(Util.USER_SESSION_KEY);
                if ((currentUser == null) && !isLoginPage && !isExpiredSessionPage) {
                    NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
                    nh.handleNavigation(facesContext, null, "loginPage");
                }

            }
        } catch (ViewExpiredException e) {
            System.out.println("Error en session"+e.getMessage());
        }
    }

    @Override
    public void beforePhase(PhaseEvent event) {

    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}
